import { defineStore } from 'pinia'
import { ref } from 'vue'
import { expireToken, setToken } from '@/utils/token'

const USER_INFO_KEY = 'user_info'

// 从 localStorage 获取初始用户信息
const getStoredUserInfo = () => {
  const storedInfo = localStorage.getItem(USER_INFO_KEY)
  return storedInfo ? JSON.parse(storedInfo) : {
    avatarUrl: '',
    nickname: '',
    userId: '',
    username: ''
  }
}

export const useUserStore = defineStore('user', () => {
  const userInfo = ref(getStoredUserInfo())

  function setUserInfo(info) {
    const newUserInfo = {
      avatarUrl: info.avatar_url,
      nickname: info.nickname,
      userId: info.user_id,
      username: info.username
    }
    userInfo.value = newUserInfo
    localStorage.setItem(USER_INFO_KEY, JSON.stringify(newUserInfo))
    setToken(info.token)
  }

  function clearUserInfo() {
    userInfo.value = {
      avatarUrl: '',
      nickname: '',
      userId: '',
      username: ''
    }
    localStorage.removeItem(USER_INFO_KEY)
    expireToken()
  }

  return {
    userInfo,
    setUserInfo,
    clearUserInfo
  }
})